package com.insigma.business.qrcode.soldier.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.insigma.business.qrcode.common.util.RedisUtils;
import com.insigma.business.qrcode.soldier.dto.AccessTokenRequestVO;
import com.insigma.business.qrcode.soldier.entity.*;
import com.insigma.business.qrcode.soldier.service.IrsService;
import com.insigma.business.qrcode.soldier.util.MD5Utils;
import com.insigma.business.qrcode.soldier.util.OkHttp3Util;
import com.insigma.business.qrcode.soldier.util.RedisLock;
import com.insigma.business.qrcode.soldier.util.SignErrException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.logging.log4j.util.Strings;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;



@Slf4j
@Service("irsServiceImpl")
public class IrsServiceImpl implements IrsService {

    private static Logger LOGGER = LoggerFactory.getLogger(IrsServiceImpl.class);

    private static String requestTokenUrl = "http://172.18.103.246:19011/gateway/app/refreshTokenByKey.htm";
    private static String refreshTokenUrl = "http://172.18.103.246:19011/gateway/app/refreshTokenBySec.htm";
    private static String appKey = "A330101229813202107000001";
    private static String appSecret = "d96fcaf75dfd45ae9c23c6d01ccc3613";


    final public static String CACHE_REQUEST_PREFIX = "irsservice:";

    private static String LOCK_KEY = CACHE_REQUEST_PREFIX + ":LOCKKEY";

    final public static String CACHE_REQUEST_SECRET = "request_secret";


    final public static String CACHE_REFRESH_SECRET = "refresh_secret";


    final public static Long CACHE_REQUEST_SECRET_TIME = 850L;


    final public static Long CACHE_REFRESH_SECRET_TIME = 171700L;


    @Value("${spring.profiles.active}")
    private String env;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisLock redisLock;

    final public static String DEAD_URL_TEMPLATE = "https://interface.zjzwfw.gov.cn/gateway/api/001003003/dataSharing/ducMTC8xe4CHd495.htm?requestTime=%s&sign=%s&appKey=%s&VC_SFZHM=%s";

    @Override
    public String safeRefreshAllSecret(Integer route) {
        boolean b = redisLock.tryLock(LOCK_KEY, 5000);
        if (b) {
            if (route == 1) {
                return refreshByRefreshKey();
            }
            return refreshAllSecret();
        } else {
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                log.error("sleep错误", e);
            }
        }
        return null;
    }


    private String refreshAllSecret() {
        log.info("refreshAllSecret");
        long requestTime = System.currentTimeMillis();

        String sign = DigestUtils.md5DigestAsHex((appKey + appSecret + requestTime).getBytes());
        String params = "appKey=" + appKey + "&requestTime=" + requestTime + "&sign=" + sign;
        String url = requestTokenUrl + "?" + params;
        System.out.println(url);
        String result = OkHttp3Util.sendByGetUrl(url);

        AccessTokenRequestVO accessTokenVO = JSONObject.parseObject(result, AccessTokenRequestVO.class);
        String requestSecret = accessTokenVO.getDatas().getRequestSecret();
        String refreshSecret = accessTokenVO.getDatas().getRefreshSecret();


        setCacheKey(CACHE_REQUEST_SECRET, requestSecret, CACHE_REQUEST_SECRET_TIME);
        setCacheKey(CACHE_REFRESH_SECRET, refreshSecret, CACHE_REFRESH_SECRET_TIME);

        return requestSecret;
    }

    private String directRefresh() {
        log.info("refreshAllSecret");
        long requestTime = System.currentTimeMillis();

        String sign = DigestUtils.md5DigestAsHex((appKey + appSecret + requestTime).getBytes());
        String params = "appKey=" + appKey + "&requestTime=" + requestTime + "&sign=" + sign;
        String url = requestTokenUrl + "?" + params;
        System.out.println(url);
        String result = OkHttp3Util.sendByGetUrl(url);

        AccessTokenRequestVO accessTokenVO = JSONObject.parseObject(result, AccessTokenRequestVO.class);
        String requestSecret = accessTokenVO.getDatas().getRequestSecret();
        return requestSecret;
    }


    private String getAppSecretByRefreshKey(String refreshKey) {
        log.info("getAppSecretByRefreshKey：{}", refreshKey);
        long requestTime = System.currentTimeMillis();

        String sign = DigestUtils.md5DigestAsHex((appKey + refreshKey + requestTime).getBytes());
        String params = "appKey=" + appKey + "&requestTime=" + requestTime + "&sign=" + sign.toLowerCase(Locale.ROOT);

        String result = OkHttp3Util.sendByGetUrl(refreshTokenUrl + "?" + params);

        AccessTokenRequestVO accessTokenVO = JSONObject.parseObject(result, AccessTokenRequestVO.class);
        if ("签名错误".equals(accessTokenVO.getMsg())) {
            throw new SignErrException("签名错误");
        }
        if (accessTokenVO.getDatas() == null) {
            return null;
        }

        String requestSecret = accessTokenVO.getDatas().getRequestSecret();
        String refreshSecret = accessTokenVO.getDatas().getRefreshSecret();


        setCacheKey(CACHE_REQUEST_SECRET, requestSecret, CACHE_REQUEST_SECRET_TIME);
        setCacheKey(CACHE_REFRESH_SECRET, refreshSecret, CACHE_REFRESH_SECRET_TIME);
        return requestSecret;
    }


    private void setCacheKey(String code, String token, Long time) {
        redisUtils.set(CACHE_REQUEST_PREFIX + code, token, time);
    }


    private Object getCacheKey(String code) {
        Object o = redisUtils.get(CACHE_REQUEST_PREFIX + code);
        return o;
    }

    @Override
    public String getSign(String timestamp) {
        String accessToken = getRealRequestSecret();
        String sign = DigestUtils.md5DigestAsHex((appKey + accessToken + timestamp).getBytes());
        return sign;
    }

    public String directGetSign(String timestamp) {
        String accessToken = directRefresh();
        String sign = DigestUtils.md5DigestAsHex((appKey + accessToken + timestamp).getBytes());
        return sign;
    }

    public String facadeGetSign(String timestamp) {
        if (Strings.isNotBlank(env)) {
            return getSign(timestamp);
        }
        return directGetSign(timestamp);
    }

    @Override
    public List<DeadInfoEntity> queryDeadInfo(String idCardNo) {
        String refreshSecret = getPersonRefreshSecret(appKey, appSecret);
        long l = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("requestTime", l);
        params.put("sign", getSign(appKey, refreshSecret, l));
        params.put("appKey", appKey);
        params.put("VC_SFZHM", idCardNo);


        String response = HttpUtil.post("https://interface.zjzwfw.gov.cn/gateway/api/001003003/dataSharing/ducMTC8xe4CHd495.htm", params);
        log.info("死亡人口信息查询入参:{}", idCardNo);
        log.info("死亡人口信息查询结果:{}", response);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = checkIsResponseSignErr(jsonObject);
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<DeadInfoEntity> result = datas.toJavaList(DeadInfoEntity.class);
                    return result;
                } else {
                    return new ArrayList<>();
                }
            }
        }

        return null;
    }

    private String checkIsResponseSignErr(JSONObject jsonObject) {
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        if ("14".equals(code) && msg.contains("签名错误")) {
            throw new SignErrException("签名错误");
        }
        return code;
    }

    @Override
    public void queryMedicalInsurance(String idCardNo) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003148/dataSharing/V1F7zse6fec2e4P8.htm?" +
                "requestTime=%s&sign=%s&appKey=%s&accrymMonth=202206&psnName=&certNo=&psnCertType=abc&endMonth=202207";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, stime, sign, appKey, idCardNo);
        String response = OkHttp3Util.sendByGetUrl(url);
        System.out.println(response);
    }

    @Override
    public ProvinceMedicalInsuranceEntity queryPersonMedicalInsurance(String name, String idCardNo) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003148/dataSharing/3D0yp5ca52ucUbda.htm?" +
                "requestTime=%s&sign=%s&appKey=%s&psnCertType=01&psnName=%s&certNo=%s";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, stime, sign, appKey, name, idCardNo);
        String response = OkHttp3Util.sendByGetUrl(url);
        JSONObject object = JSON.parseObject(response);
        if ("00".equals(object.getString("code"))) {
            String datas = object.getString("datas");
            JSONObject object1 = JSONObject.parseObject(datas);
            ProvinceMedicalInsuranceEntity data = object1.getObject("data", ProvinceMedicalInsuranceEntity.class);
            return data;
        }
        return null;
    }

    @Override
    public void queryPeition(String idCardNo) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003047/dataSharing/letterOfVisitInfo.htm?" +
                "requestTime=%s&sign=%s&appKey=%s&uniscIdOrName=%s";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, stime, sign, appKey, idCardNo);
        String response = OkHttp3Util.sendByGetUrl(url);
        System.out.println(response);
    }

    @Override
    public void queryWeifa(String idCardNo) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003001029/dataSharing/fgwHjBiz019Zdsswfajdsrmd.htm?" +
                "requestTime=%s&sign=%s&appKey=%s&nsrmc=%s";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, stime, sign, appKey, idCardNo);
        String response = OkHttp3Util.sendByGetUrl(url);
        System.out.println(response);
    }

    @Override
    public List<EducationEntity> queryEducationInfo(String realName, String idCardNo) {
        String refreshSecret = getPersonRefreshSecret(appKey, appSecret);
        long l = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("requestTime", l);
        params.put("sign", getSign(appKey, refreshSecret, l));
        params.put("appKey", appKey);
        params.put("zjhm", idCardNo);
        params.put("xm", realName);


        String res = HttpUtil.post("http://172.18.103.246:19010/gateway/api/001003001029/dataSharing/974M4fpP6kF938k1.htm", params);
        log.info("学历信息{}", res);
        JSONObject object = JSONObject.parseObject(res);
        if ("00".equals(object.getString("code"))) {
            String datas = object.getString("datas");
            Document document = null;
            try {
                document = DocumentHelper.parseText(datas);
                Element element = document.getRootElement();
                Iterator iterator = element.elementIterator();

                List<EducationEntity> result = Lists.newArrayList();
                while (iterator.hasNext()) {
                    Element next = (Element) iterator.next();
                    EducationEntity entity = new EducationEntity();
                    entity.setCc(next.element("cc").getText());
                    entity.setRxrq(next.element("rxrq").getText());
                    entity.setXxxs(next.element("xxxs").getText());
                    entity.setXm(next.element("xm").getText());
                    entity.setZsbh(next.element("zsbh").getText());
                    entity.setByrq(next.element("byrq").getText());
                    entity.setZjhm(next.element("zjhm").getText());
                    entity.setZymc(next.element("zymc").getText());
                    entity.setYxmc(next.element("yxmc").getText());
                    result.add(entity);
                }
                return result;
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public List<DeadInfoIrsEntity> queryDeadCremateInfo(String idCardNo) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003010/dataSharing/cremationInfo.htm?" +
                "requestTime=%s&cardId=%s&sign=%s&appKey=%s";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, stime, idCardNo, sign, appKey);
        String response = OkHttp3Util.sendByGetUrl(url);
        JSONObject object = JSONObject.parseObject(response);

        checkIsResponseSignErr(object);
        if ("00".equals(object.getString("code"))) {
            JSONArray datas = object.getJSONArray("datas");
            if (datas != null) {
                List<DeadInfoIrsEntity> deadInfoIrsEntities = datas.toJavaList(DeadInfoIrsEntity.class);
                return deadInfoIrsEntities;
            }
        }
        return null;
    }

    @Override
    public List<InsuredInfoEntity> queryInusreListOfIrs(String idCardNo, String name) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003001/dataSharing/DB6f9g1FA28c7g4f.htm?" +
                "requestTime=%s&sign=%s&appKey=%s&interfaceCode=I30701600003029/2861&aac002=%s&aac003=%s&materialName=个人缴费" +
                "&additional={}&intext={\"aac003\":\"\",\"aac002\":\"\"}";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, stime, sign, appKey, idCardNo, name);
        String response = OkHttp3Util.sendByGetUrl(url);
        JSONObject object = JSONObject.parseObject(response);

        checkIsResponseSignErr(object);
        if ("00".equals(object.getString("code"))) {
            JSONArray datas = object.getJSONArray("datas");
            if (datas != null) {

            }
        }
        return null;
    }

    @Override
    public List<GaPopulationIrsEntity> queryGaPopulation(String idCardNo, String name) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/popInfo.htm?" +
                "appKey=%s&sign=%s&requestTime=%s&cardId=%s";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, appKey, sign, stime, idCardNo);
        String response = OkHttp3Util.sendByGetUrl(url);
        JSONObject object = JSONObject.parseObject(response);

        checkIsResponseSignErr(object);
        if ("00".equals(object.getString("code"))) {
            JSONArray datas = object.getJSONArray("datas");
            if (datas != null) {
                List<GaPopulationIrsEntity> deadInfoIrsEntities = datas.toJavaList(GaPopulationIrsEntity.class);
                return deadInfoIrsEntities;
            }
        }
        return null;
    }

    @Override
    public List<IrsSubsistenceEntity> queryDibao(String idCardNo) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003010/dataSharing/lowestRescueNewInfo.htm?" +
                "requestTime=%s&sign=%s&appKey=%s&aHAP0015=%s&bHAX0114=%s&bHAX0115=%s";
        String refreshSecret = getPersonRefreshSecret(appKey, appSecret);
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = getSign(appKey, refreshSecret, l);

        Date date = DateUtils.addMonths(new Date(), -2);
        int year = DateUtil.year(date);
        int month = DateUtil.month(date);

        String url = String.format(urlbase, stime, sign, appKey, idCardNo, String.valueOf(year), String.valueOf(month));
        String response = OkHttp3Util.sendByGetUrl(url);
        JSONObject object = JSONObject.parseObject(response);

        checkIsResponseSignErr(object);
        if ("00".equals(object.getString("code"))) {
            JSONArray datas = object.getJSONArray("datas");
            if (datas != null) {
                List<IrsSubsistenceEntity> deadInfoIrsEntities = datas.toJavaList(IrsSubsistenceEntity.class);
                return deadInfoIrsEntities;
            } else {
                return new ArrayList<>();
            }
        }
        return null;
    }

    @Override
    public List<IrsLowSideEntity> queryDibian(String idCardNo, String name) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003010/dataSharing/edgeRescuePerBasicInfo.htm?" +
                "requestTime=%s&sign=%s&appKey=%s&name=%s&cardId=%s";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, stime, sign, appKey, name, idCardNo);
        String response = OkHttp3Util.sendByGetUrl(url);
        JSONObject object = JSONObject.parseObject(response);

        checkIsResponseSignErr(object);
        if ("00".equals(object.getString("code"))) {
            JSONArray datas = object.getJSONArray("datas");
            if (datas != null) {
                List<IrsLowSideEntity> deadInfoIrsEntities = datas.toJavaList(IrsLowSideEntity.class);
                return deadInfoIrsEntities;
            } else {
                return new ArrayList<>();
            }

        }
        return null;
    }

    @Override
    public List<IrsExtremelyPoorEntity> queryTekun(String idCardNo, String name) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003010/dataSharing/extremelyPoorBasicInfo.htm?" +
                "requestTime=%s&sign=%s&appKey=%s&name=%s&cardId=%s";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, stime, sign, appKey, name, idCardNo);
        String response = OkHttp3Util.sendByGetUrl(url);
        JSONObject object = JSONObject.parseObject(response);

        checkIsResponseSignErr(object);
        if ("00".equals(object.getString("code"))) {
            JSONArray datas = object.getJSONArray("datas");
            if (datas != null) {
                List<IrsExtremelyPoorEntity> deadInfoIrsEntities = datas.toJavaList(IrsExtremelyPoorEntity.class);
                return deadInfoIrsEntities;
            } else {
                return new ArrayList<>();
            }
        }
        return null;
    }

    public void flexibleEmployment(String realName, String idCardNo) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003085/dataSharing/bbd9d2r8T35474i1.htm?" +
                "requestTime=%s&sign=%s&appKey=%s&aac003=%s&aac002=%s&adc111=021";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, stime, sign, appKey, realName, idCardNo);
        String response = OkHttp3Util.sendByGetUrl(url);
        JSONObject object = JSONObject.parseObject(response);
        System.out.println();
    }

    public void dibao(String realName, String idCardNo) {
        String urlbase = "http://172.18.103.246:19010/gateway/api/001003001029/certificate/NefZePFa11Oa5O34.htm?" +
                "requestTime=%s&sign=%s&appKey=%s&Organization_Id=test&User_ID=%s&User_Name=%s&Organization=test&sfhm=%s";
        long l = System.currentTimeMillis();
        String stime = String.valueOf(l);
        String sign = facadeGetSign(stime);

        String url = String.format(urlbase, stime, sign, appKey, idCardNo, realName, idCardNo);
        String response = OkHttp3Util.sendByGetUrl(url);
        List<String> api = Lists.newArrayList();
        JSONObject object = JSONObject.parseObject(response);
        System.out.println();
    }

    public String getRealRequestSecret() {
        Object requestSecret = getCacheKey(CACHE_REQUEST_SECRET);
        if (requestSecret == null) {
            return refreshByRefreshKey();
        } else {
            return requestSecret.toString();
        }
    }

    private String refreshByRefreshKey() {

        Object refreshCacheObj = getCacheKey(CACHE_REFRESH_SECRET);
        if (refreshCacheObj != null) {

            String requestKey = getAppSecretByRefreshKey(refreshCacheObj.toString());
            if (requestKey == null) {
                return refreshAllSecret();
            }
            return requestKey;
        } else {

            return safeRefreshAllSecret(3);
        }
    }


    public void orcComponent(String path, String name) {
        long currentTimeMillis = System.currentTimeMillis();
        System.out.println(currentTimeMillis);
        String s = DigestUtils.md5DigestAsHex(("c25ea31c3cda45209f0c5b502198e5ae" + "05cc923a97de40898c8ba91637e1f9e2" + currentTimeMillis).getBytes());

        Map<String, String> header = Maps.newHashMap();
        header.put("zjgxfwxt-interface-code", "atg.biz.tess.1");
        header.put("zjgxfwxt-access-key", "c25ea31c3cda45209f0c5b502198e5ae");
        header.put("zjgxfwxt-sign", s);
        header.put("zjgxfwxt-time", String.valueOf(currentTimeMillis));

        OkHttp3Util.upload("http://172.18.103.246:19010/gateway/component/routing/agent.htm", path, name);
    }


    public void qrShixinren() {
        long currentTimeMillis = System.currentTimeMillis();
        System.out.println(currentTimeMillis);
        String s = DigestUtils.md5DigestAsHex(("bed055fd9a0e42dda17bc8fbdaa74652" + "ecae29eb7d0f47fc9c956a47e5d2c400" + currentTimeMillis).getBytes());

        Map<String, String> header = Maps.newHashMap();
        header.put("zjgxfwxt-interface-code", "atg.biz.yzsxmd.2");
        header.put("zjgxfwxt-access-key", "bed055fd9a0e42dda17bc8fbdaa74652");
        header.put("zjgxfwxt-sign", s);
        header.put("zjgxfwxt-time", String.valueOf(currentTimeMillis));

        String body = "{\n" +
                "    \"appKey\": \"dddefb16-b946-4b12-bc12-9eea4924\",\n" +
                "    \"uscc\": \"91330000074004186Q\",\n" +
                "    \"ztlx\": \"E\",\n" +
                "    \"ztmc\": \"浙江星天发展实业有限公司\",\n" +
                "    \"matterName\": \"经营许可\",\n" +
                "    \"matterCode\": \"许可-0000-000-01\",\n" +
                "    \"purpose\": \"行政许可查询\",\n" +
                "    \"deptName\": \"工商局\",\n" +
                "    \"deptCode\": \"11211000006526097B\"\n" +
                "}";
        String s1 = OkHttp3Util.sendByPostJson("http://172.18.103.246:19010/gateway/component/routing/agent.htm", body, header);
        System.out.println(s1);
    }


    public void qt5sm() {
        long currentTimeMillis = System.currentTimeMillis();
        System.out.println(currentTimeMillis);
        String ak = "874ad870f152457a98291112417db474";
        String sk = "85a2a94f6f214d9c888e5c1fb6962aba";
        String s = DigestUtils.md5DigestAsHex((ak + sk + currentTimeMillis).getBytes());

        Map<String, String> header = Maps.newHashMap();
        header.put("zjgxfwxt-interface-code", "WSYJPG");
        header.put("zjgxfwxt-access-key", ak);
        header.put("zjgxfwxt-sign", s);
        header.put("zjgxfwxt-time", String.valueOf(currentTimeMillis));

        String s1 = OkHttp3Util.sendByGetUrlWithHeader("http://172.18.103.246:19010/gateway/component/routing/agent.htm" +
                "?pageSize=100&start=1&orderType=2&paraCode=ZHPGZS&level=3&date=2021-10&dateType=3&c=0", header);
        System.out.println();
    }


    public static final String REFRESHSECRETKEY_CACHE_KEY = "irs:refreshsecretKey:";

    /**
     * 获取请求秘钥
     *
     * @param appKey
     * @param secretKey
     * @return
     */
    private String getPersonRefreshSecret(String appKey, String secretKey) {


        Object object = redisUtils.get(REFRESHSECRETKEY_CACHE_KEY + appKey);
        if (ObjectUtil.isNotEmpty(object)) {
            return (String) object;
        }

        Long requestTime = System.currentTimeMillis();
        String sign = MD5Utils.encodeByMD5(appKey + secretKey + requestTime);

        String url = "http://172.18.103.246:19010/gateway/app/refreshTokenByKey.htm?"
                + "requestTime=" + requestTime + "&appKey=" + appKey + "&sign=" + sign;

        TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        HttpClientBuilder clientBuilder = HttpClients.custom();
        CloseableHttpClient httpClient = clientBuilder.setSSLSocketFactory(sslsf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appKey", appKey);
        jsonObject.put("sign", sign);
        jsonObject.put("requestTime", requestTime);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(jsonObject, requestHeaders);
        JSONObject json = restTemplate.postForObject(url, requestEntity, JSONObject.class);
        if ("00".equals(json.getString("code"))) {
            String requestSecret = json.getJSONObject("datas").getString("requestSecret");
            redisUtils.set(REFRESHSECRETKEY_CACHE_KEY, requestSecret, 14 * 60);
            return requestSecret;
        }

        log.error("IrsUtil-秘钥请求失败：{}", json);
        return null;
    }


    @Override
    public List<FloatingPopulationEntity> queryFloatingPopulationList(String idCardNo, String name) {
        String refreshSecret = getPersonRefreshSecret(appKey, appSecret);
        long l = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("requestTime", l);
        params.put("sign", getSign(appKey, refreshSecret, l));
        params.put("appKey", appKey);
        params.put("sfzh", idCardNo);


        String response = HttpUtil.post("http://172.18.103.246:19010/gateway/api/proxy/001003001/highspeed/3F9a8b2UQde8QMe1.htm", params);
        log.info("流动人口查询：{}", response);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<FloatingPopulationEntity> result = datas.toJavaList(FloatingPopulationEntity.class);
                    return result;
                } else {
                    return new ArrayList<>();
                }
            }
        }
        return null;
    }


    @Override
    public List<UntrustworthyEntity> queryUntrustworthy(String idCardNo, String name) {
        String refreshSecret = getPersonRefreshSecret(appKey, appSecret);
        long l = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("requestTime", l);
        params.put("sign", getSign(appKey, refreshSecret, l));
        params.put("appKey", appKey);
        params.put("cardId", idCardNo);
        params.put("name", name);
        params.put("executorNature", "自然人");
        String response = HttpUtil.post("http://172.18.103.246:19010/gateway/api/001021001/dataSharing/disrespectfulExecutorInfo.htm", params);

        log.info("查询失信执行人信息返回结果：{}" + response);

        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<UntrustworthyEntity> untrustworthyEntities = datas.toJavaList(UntrustworthyEntity.class);
                    return untrustworthyEntities;
                } else {
                    return new ArrayList<UntrustworthyEntity>();
                }
            }
        }
        return null;
    }


    @Override
    public List<CommunityCorrectionEntity> queryCommunityCorrectionList(String idCardNo) {

        String refreshSecret = getPersonRefreshSecret(appKey, appSecret);
        long l = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("requestTime", l);
        params.put("sign", getSign(appKey, refreshSecret, l));
        params.put("appKey", appKey);
        params.put("sfzh", idCardNo);


        String response = HttpUtil.post("http://172.18.103.246:19010/gateway/api/001021001/dataSharing/c7B73IBa4Y6v13V0.htm", params);
        log.info("矫正信息:{}", response);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<CommunityCorrectionEntity> communityCorrectionEntities = datas.toJavaList(CommunityCorrectionEntity.class);
                    return communityCorrectionEntities;
                }
            }
        }
        return null;
    }

    @Override
    public List<ShareholderEntity> queryShareholderList(String idCardNo) {
        String refreshSecret = getPersonRefreshSecret(appKey, appSecret);
        long l = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("requestTime", l);
        params.put("sign", getSign(appKey, refreshSecret, l));
        params.put("appKey", appKey);
        params.put("zjhm", idCardNo);
//        params.put("xm", name);
        String response = HttpUtil.post("http://172.18.103.246:19010/gateway/api/001003033/dataSharing/RubHnd10UefF2244.htm", params);
        log.info("查询法人信息:{}", response);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONObject("datas").getJSONArray("result");
                if (datas != null) {
                    List<ShareholderEntity> entityList = datas.toJavaList(ShareholderEntity.class);
                    return entityList;
                }
            }
        }
        return null;
    }

    @Override
    public List<EnterpriseInfoEntity> queryEnterpriseList(String uniscid) {
        String refreshSecret = getPersonRefreshSecret(appKey, appSecret);
        long l = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("requestTime", l);
        params.put("sign", getSign(appKey, refreshSecret, l));
        params.put("appKey", appKey);
        params.put("uniscId", uniscid);

        String response = HttpUtil.post("http://172.18.103.246:19010/gateway/api/enterpriseInfo.htm", params);
        log.info("查询企业信息：{}", response);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<EnterpriseInfoEntity> entityList = datas.toJavaList(EnterpriseInfoEntity.class);
                    return entityList;
                }
            }
        }
        return Lists.newArrayList();
    }

    @Override
    public List<EnterpriseInfoEntity> queryEnterpriseListByName(String companyName) {
        String refreshSecret = getPersonRefreshSecret(appKey, appSecret);
        long l = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("requestTime", l);
        params.put("sign", getSign(appKey, refreshSecret, l));
        params.put("appKey", appKey);
        params.put("companyName", companyName);

        String response = HttpUtil.post("http://172.18.103.246:19010/gateway/api/enterpriseInfo.htm", params);
        log.info("查询企业信息：{}", response);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<EnterpriseInfoEntity> entityList = datas.toJavaList(EnterpriseInfoEntity.class);
                    return entityList;
                }
            }
        }
        return Lists.newArrayList();
    }


    @Override
    public List<SocialSecurityEntity> querySocialSecurity(String idCardNo, String name) {
        String refreshSecret = getPersonRefreshSecret(appKey, appSecret);
        long l = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("requestTime", l);
        params.put("sign", getSign(appKey, refreshSecret, l));
        params.put("appKey", appKey);
        params.put("AAC002", idCardNo);


        String response = HttpUtil.post("http://172.18.103.246:19010/gateway/api/001003001/dataSharing/fA9d5cbdPOej72Q4.htm", params);
        log.info("查询社保信息：{}", response);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<SocialSecurityEntity> result = datas.toJavaList(SocialSecurityEntity.class);
                    return result;
                } else {
                    return new ArrayList<>();
                }
            }
        }
        return null;
    }

    private static String getSign(String appKey, String appSecret, long timestamp) {
        String encode = MD5Utils.encodeByMD5(appKey + appSecret + timestamp);
//        System.out.println(encode);
        return encode;
    }

    public static void main(String[] args) {
        List<IrsSubsistenceEntity> irsSubsistenceEntities = new IrsServiceImpl().queryDibao("330105196306080332");
        System.out.println();
    }
}
